package com.glxt.controller;

import com.glxt.model.UserBean;
import com.glxt.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
public class UserController {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private UserService userServiceImpl;
    @PostMapping("/goregister")
    @ResponseBody
    public int goregister(UserBean users,@RequestParam("name") String uname,@RequestParam("password") String upass){
        System.out.println("name " + uname+",password :" + upass);
        users.setUserName(uname);
        users.setUserPass(upass);
        users.setUserRole("普通用户");
        userServiceImpl.register(users);
        return 1;
    }
    @GetMapping("/Temp_Bean_json")
    @ResponseBody
    public List<UserBean> Temp_Bean_json(Model m){

        String sql = "select * from tbluser";
        BeanPropertyRowMapper<UserBean> rowMapper = new BeanPropertyRowMapper<UserBean>(UserBean.class);

        List<UserBean> UserList = jdbcTemplate.query(sql,rowMapper);
        return UserList;
    }
    @GetMapping("/edituser")
    public String edituser(Model m){
        List<UserBean> UserList = (List<UserBean>) userServiceImpl.findall();
        m.addAttribute("Result",UserList);
        return "edituser";
    }
    @GetMapping("/godel/{id}")
    public String deluser(@PathVariable int id){
        userServiceImpl.delUser(id);
        return "redirect:/edituser";
    }
    @RequestMapping("/goupdate/{id}")
    public String goupdate(@PathVariable int id,Model model){
        UserBean user = userServiceImpl.findByid(id);
        model.addAttribute("user",user);
        return "/updateuser";
    }
    @GetMapping("/update")
    public String update(UserBean users,@RequestParam("id") int id
            ,@RequestParam("name") String uname,@RequestParam("pass") String upass,@RequestParam("role") String urole){
        users.setId(id);
        users.setUserName(uname);
        users.setUserPass(upass);
        users.setUserRole(urole);
        userServiceImpl.updateUser(users);
        return "redirect:/edituser";
    }

}
